"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : accept_empty_str
Case Name   : 设置behavior_compat_options为accept_empty_str，copy to/from语句测试
Create At   : 2023.08.04
Owner       : opentestcase005
Description :
    1.设置参数为accept_empty_str
    2.建表并插入数据
    3.查询
    4.将表数据导入文件以csv格式
    5.清空表数据
    6.将文件内容导入表
    7.查询
    8.清空表数据
    9.再次插入数据
    10.将表数据导入文件以text格式
    11.查询
    12.清空表数据
    13.再次插入数据
    14.将表数据导入文件以binary格式
    15.查询
    16.清理环境
Expect      :
    1.成功
    2.成功
    3.空字符串原样显示，不是null，返回false
    4.成功
    5.成功
    6.成功
    7.和导入前结果一样
    8.成功
    9.成功
    10.成功
    11.成功，设置参数时空串原样处理，和null不同
    12.成功
    13.成功
    14.成功
    15.成功，设置参数时空串原样处理，和null不同
    16.成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class CopyFile(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node(node='PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.copy_dir_path1 = os.path.join(macro.DB_INSTANCE_PATH,
                                           't_csv.data')
        self.copy_dir_path2 = os.path.join(macro.DB_INSTANCE_PATH,
                                           't_text.data')
        self.copy_dir_path3 = os.path.join(macro.DB_INSTANCE_PATH,
                                           't_binary.data')
        self.default_value = self.common.show_param('behavior_compat_options')
        self.tb_name = "tb_guc0032"

    def test_copy_file(self):
        text = '-----step1:设置参数为accept_empty_str;expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('reload',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            "behavior_compat_options "
                                            "='accept_empty_str'")
        self.log.info(mod_msg)
        self.assertTrue(mod_msg)
        sql_cmd = "show behavior_compat_options;"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertEqual('accept_empty_str',
                         sql_res.splitlines()[-2].strip(), '查询失败')

        text = '-----step2:建表并插入数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f'''drop table if exists {self.tb_name};
        create table {self.tb_name} (t_varchar varchar, t_text text, \
        t_char char(10), t_bytea bytea);
        insert into {self.tb_name} values('abc', 'abc', 'abc', 'abc'), \
        ('   ', '   ', '   ', '   '), ('', '', '', '');'''
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, sql_res,
                      '执行失败:' + text)
        self.assertIn('INSERT 0 3', sql_res, '执行失败:' + text)

        text = '-----step3:查询;expect:空字符串原样显示，不是null，返回false-----'
        self.log.info(text)
        sql_cmd = f"select t_varchar is null as varchar_is_null, " \
                  f"t_text is null as text_is_null, " \
                  f"t_char is null as char_is_null, " \
                  f"t_bytea is null as bytea_is_null from {self.tb_name};"
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        rows, _ = self.common.parse_sql_query_res(sql_res)
        expect = [['f', 'f', 'f', 'f'], ['f', 'f', 'f', 'f'],
                  ['f', 'f', 'f', 'f']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '-----step4:将表数据导入文件以csv格式;expect:copy成功-----'
        self.log.info(text)
        sql_cmd = f"copy {self.tb_name} to '{self.copy_dir_path1}' " \
                  f"with(format 'csv');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('COPY 3', sql_res, '执行失败:' + text)

        text = '-----step5:清空表数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"truncate table {self.tb_name};"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('TRUNCATE', sql_res, '执行失败:' + text)

        text = '-----step6:将文件内容导入表;expect:copy成功-----'
        self.log.info(text)
        sql_cmd = f"copy {self.tb_name} from '{self.copy_dir_path1}' " \
                  f"WITH(format 'csv');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('COPY 3', sql_res, '执行失败:' + text)

        text = '-----step7:查询;expect:和导入前结果一样-----'
        self.log.info(text)
        sql_cmd = f"select t_varchar is null as varchar_is_null, " \
                  f"t_text is null as text_is_null, " \
                  f"t_char is null as char_is_null, " \
                  f"t_bytea is null as bytea_is_null from {self.tb_name};"
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        rows, _ = self.common.parse_sql_query_res(sql_res)
        expect = [['f', 'f', 'f', 'f'], ['f', 'f', 'f', 'f'],
                  ['f', 'f', 'f', 'f']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '-----step8:清空表数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"truncate table {self.tb_name};"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('TRUNCATE', sql_res, '执行失败:' + text)

        text = '-----step9:再次插入数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"insert into {self.tb_name} " \
                  f"values('abc', 'abc', 'abc', 'abc')," \
                  f"('   ', '   ', '   ', '   '), ('', '', '', '');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('INSERT', sql_res, '执行失败:' + text)

        text = '-----step10:将表数据导入文件以text格式;expect:copy成功-----'
        self.log.info(text)
        sql_cmd = f"copy {self.tb_name} to '{self.copy_dir_path2}' " \
                  f"with(format 'text');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('COPY 3', sql_res, '执行失败:' + text)

        text = '-----step11:查询;expect:成功，设置参数时空串原样处理，和null不同-----'
        self.log.info(text)
        sql_cmd = f"select t_varchar is null as varchar_is_null, " \
                  f"t_text is null as text_is_null, " \
                  f"t_char is null as char_is_null, " \
                  f"t_bytea is null as bytea_is_null from {self.tb_name};"
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        rows, _ = self.common.parse_sql_query_res(sql_res)
        expect = [['f', 'f', 'f', 'f'], ['f', 'f', 'f', 'f'],
                  ['f', 'f', 'f', 'f']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '-----step12:清空表数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"truncate table {self.tb_name};"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('TRUNCATE', sql_res, '执行失败:' + text)

        text = '-----step13:再次插入数据;expect:成功-----'
        self.log.info(text)
        sql_cmd = f"insert into {self.tb_name} " \
                  f"values('abc', 'abc', 'abc', 'abc')," \
                  f"('   ', '   ', '   ', '   '), ('', '', '', '');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('INSERT', sql_res, '执行失败:' + text)

        text = '-----step14:将表数据导入文件以binary格式;expect:copy成功-----'
        self.log.info(text)
        sql_cmd = f"copy {self.tb_name} to '{self.copy_dir_path3}' " \
                  f"with(format 'binary');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn('COPY 3', sql_res, '执行失败:' + text)

        text = '-----step15:查询;expect:成功，设置参数时空串原样处理，和null不同-----'
        self.log.info(text)
        sql_cmd = f"select t_varchar is null as varchar_is_null, " \
                  f"t_text is null as text_is_null, " \
                  f"t_char is null as char_is_null, " \
                  f"t_bytea is null as bytea_is_null from {self.tb_name};"
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        rows, _ = self.common.parse_sql_query_res(sql_res)
        expect = [['f', 'f', 'f', 'f'], ['f', 'f', 'f', 'f'],
                  ['f', 'f', 'f', 'f']]
        self.assertEqual(rows, expect, '执行失败' + text)

    def tearDown(self):
        text = '-----step16:清理环境;expect:清理环境成功-----'
        self.log.info(text)
        sql_cmd = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name};")
        self.log.info(sql_cmd)
        rm_cmd = f'''rm -rf {self.copy_dir_path1} {self.copy_dir_path2} \
        {self.copy_dir_path3}'''
        self.log.info(rm_cmd)
        msg = self.common.get_sh_result(self.pri_user, rm_cmd)
        self.log.info(msg)
        mod_msg = self.pri_sh.execute_gsguc('reload',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            f"behavior_compat_options "
                                            f"='{self.default_value}'")
        self.log.info(mod_msg)
        self.assertTrue(mod_msg)
        self.assertEqual(len(msg), 0, '执行失败:' + text)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, sql_cmd)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
